/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.codec;

import com.lvyh.lightframe.common.RpcContext;
import com.lvyh.lightframe.common.ext.ExtensionLoaderFactory;
import com.lvyh.lightframe.core.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class NettyDecoder extends ByteToMessageDecoder {

    private Class<?> genericClass;
    private Serializer serializer;

    public NettyDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
        this.serializer = ExtensionLoaderFactory.getExtensionLoader(Serializer.class).getExtension(RpcContext.getSerializer());
    }

    @Override
    public final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }

        //Mark start position of byte stream
        in.markReaderIndex();

        //Gets byte stream length of data
        int dataLength = in.readInt();
        if (dataLength < 0) {
            ctx.close();
        }

        // Length check, byte stream length at least dataLength bytes,
        // less than dataLength bytes will wait for the next byte stream.
        if (in.readableBytes() < dataLength) {

            //Length check: the length of byte stream is less than the length of data packet,
            //indicating that the data packet is unpacked and waiting for the next byte stream.
            //Reset read index to 0
            in.resetReaderIndex();
            return;
        }

        byte[] data = new byte[dataLength];
        in.readBytes(data);

        Object obj = serializer.deserialize(data, genericClass);
        out.add(obj);
    }
}
